var gulp = require('gulp');
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var jade = require('gulp-jade');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var declare = require('gulp-declare');
var _ = require('lodash');
var minifyCss = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var beep = require('beepbeep');

var sass = require('gulp-sass');
var postcss      = require('gulp-postcss');
var autoprefixer = require('autoprefixer');

function relativePaths(parentPath, paths) {
    return _.map(paths, function (p) {
        return parentPath + p
    });
}

function errorHandler(err) {
    beep(2);
    console.error(err.toString());
}

function enhancedSass(srcPaths, concatFile, descPath) {
    gulp.src(srcPaths)
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(sass())
        .pipe(concat(concatFile))
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(descPath));
}

function coffeeScript(srcPaths, concatFile, destPath) {
    var p = gulp.src(srcPaths)
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(sourcemaps.init())
        .pipe(coffee());
    // .pipe(uglify())
    p = concatFile && p.pipe(concat(concatFile)) || p;
    p.pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(destPath));
}

gulp.task('style', [], function () {
    gulp.src(['src/**/**.scss'])
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(sass())
        .pipe(minifyCss({compatibility: 'ie8'}))
        .pipe(postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('dist/'));
});

gulp.task('script', [], function () {
    gulp.src(['src/**/**.coffee'])
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(sourcemaps.init())
        .pipe(coffee())
        .pipe(gulp.dest('dist/'));
});

gulp.task('lib', [], function () {
    gulp.src("lib/**").pipe(gulp.dest('dist/lib'));
});

gulp.task('img', [], function () {
    return gulp.src("img/**").pipe(gulp.dest('dist/img'));
});

gulp.task('test', [], function () {
    gulp.src(['test/**/**.jade'])
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(jade())
        .pipe(gulp.dest('dist/test/'));
});
gulp.task('watch', ['default'], function () {
    gulp.watch('src/**/**.scss', ['style']);
    gulp.watch('src/**/**.coffee', ['script']);
    gulp.watch('img/**', ['img']);
    gulp.watch('lib/**', ['lib']);
    gulp.watch('test/**', ['test']);
});

gulp.task('default', ['style', 'script', 'lib', 'img', 'test']);